<template>
  <div class="admin-user-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>用户管理</h2>
          <div style="display: flex; align-items: center; gap: 10px;">
            <el-select v-model="getUsersForm.role" placeholder="按角色筛选" clearable filterable @change="refreshUsers">
              <el-option label="全部" value=""></el-option>
              <el-option label="系统管理员" value="admin"></el-option>
              <el-option label="客户" value="customer"></el-option>
              <el-option label="采购员" value="purchaser"></el-option>
              <el-option label="销售员" value="salesman"></el-option>
              <el-option label="配送员" value="deliveryman"></el-option>
            </el-select>
            <el-button type="primary" @click="refreshUsers">刷新列表</el-button>
          </div>
        </div>
      </template>

      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="5" animated />
      </div>
      <div v-else>
        <el-alert
          v-if="errorMessage"
          :title="errorMessage"
          type="error"
          show-icon
          :closable="true"
          @close="errorMessage = ''"
        />

        <el-table :data="users" style="width: 100%" v-loading="tableLoading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="150" />
        <el-table-column prop="role" label="角色" width="150">
          <template #default="{ row }">
            <el-tag :type="getRoleType(row.role)">{{ getRoleText(row.role) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="phone" label="电话" width="150" />
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleEditRole(row)"
            >
              修改角色
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDeleteUser(row)"
              style="margin-left: 8px;"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 修改角色对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="修改用户角色"
      width="30%"
    >
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="用户名">
          <span>{{ editForm.username }}</span>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="editForm.role" placeholder="请选择角色" filterable>
            <el-option
              v-for="role in roleOptions"
              :key="role.value"
              :label="role.label"
              :value="role.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUpdateRole" :loading="updateRoleLoading">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import { getToken } from '@/utils/auth'

const users = ref([])
const dialogVisible = ref(false)
const loading = ref(false)
const tableLoading = ref(false)
const updateRoleLoading = ref(false)
const errorMessage = ref('')

const editForm = ref({
  id: null,
  username: '',
  role: ''
})

const roleOptions = [
  { value: 'admin', label: '系统管理员' },
  { value: 'purchaser', label: '采购员' },
  { value: 'salesman', label: '销售员' },
  { value: 'deliveryman', label: '配送员' },
  { value: 'customer', label: '客户' }
]

const getRoleType = (role) => {
  const types = {
    admin: 'danger',
    purchaser: 'warning',
    salesman: 'success',
    deliveryman: 'info',
    customer: ''
  }
  return types[role] || ''
}

const getRoleText = (role) => {
  const texts = {
    admin: '系统管理员',
    purchaser: '采购员',
    salesman: '销售员',
    deliveryman: '配送员',
    customer: '客户'
  }
  return texts[role] || role
}

// 用户列表查询表单
const getUsersForm = ref({
  role: '',
  username: '',
  email: '',
  phone: ''
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 获取用户列表
const refreshUsers = async () => {
  try {
    loading.value = true
    tableLoading.value = true
    errorMessage.value = ''
    // 检查token
    const token = getToken()
    if (!token) {
      errorMessage.value = '未登录或登录已过期，请重新登录'
      ElMessage.warning('请先登录')
      return
    }
    // 获取所有用户数据
    const response = await request.get('/api/users/all/')
    let allData = []
    if (Array.isArray(response)) {
      allData = response
    } else if (response.results && Array.isArray(response.results)) {
      allData = response.results
    } else if (response.items && Array.isArray(response.items)) {
      allData = response.items
    } else if (typeof response === 'object') {
      const arrayProps = Object.keys(response).filter(key => Array.isArray(response[key]))
      if (arrayProps.length > 0) {
        allData = response[arrayProps[0]]
      }
    }
    window.allUsersData = allData
    filterUsers()
  } catch (error) {
    console.error('获取用户列表失败:', error)
    users.value = []
    total.value = 0
    errorMessage.value = `获取用户列表失败: ${error.response?.data?.detail || error.message}`
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
    tableLoading.value = false
  }
}

// 前端全量过滤和分页
const filterUsers = () => {
  let filtered = window.allUsersData || []
  // 角色等值匹配
  if (getUsersForm.value.role) {
    filtered = filtered.filter(u => u.role === getUsersForm.value.role)
  }
  // 用户名模糊匹配
  if (getUsersForm.value.username) {
    const q = getUsersForm.value.username.toLowerCase().trim()
    filtered = filtered.filter(u => (u.username || '').toLowerCase().includes(q))
  }
  // 邮箱模糊匹配
  if (getUsersForm.value.email) {
    const q = getUsersForm.value.email.toLowerCase().trim()
    filtered = filtered.filter(u => (u.email || '').toLowerCase().includes(q))
  }
  // 电话模糊匹配
  if (getUsersForm.value.phone) {
    const q = getUsersForm.value.phone.toLowerCase().trim()
    filtered = filtered.filter(u => (u.phone || '').toLowerCase().includes(q))
  }
  total.value = filtered.length
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  users.value = filtered.slice(start, end)
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  filterUsers()
}

// 处理每页数量变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  filterUsers()
}

// 打开编辑角色对话框
const handleEditRole = (user) => {
  console.log('编辑用户角色:', user)
  editForm.value = {
    id: user.id,
    username: user.username,
    role: user.role
  }
  dialogVisible.value = true
}

// 更新用户角色
const handleUpdateRole = async () => {
  try {
    updateRoleLoading.value = true
    console.log('更新用户角色:', editForm.value)
    
    // 检查token
    const token = getToken()
    if (!token) {
      ElMessage.warning('请先登录')
      return
    }
    
    // 使用正确的API路径 - 与ApiTest.vue保持一致
    const response = await request.put(`/api/users/${editForm.value.id}/update-role/`, {
      role: editForm.value.role
    })
    
    console.log('角色更新响应:', response)
    ElMessage.success('角色更新成功')
    dialogVisible.value = false
    refreshUsers()
  } catch (error) {
    console.error('角色更新失败:', error)
    console.error('错误详情:', error.response?.data || error.message)
    ElMessage.error(`角色更新失败: ${error.response?.data?.detail || error.message}`)
  } finally {
    updateRoleLoading.value = false
  }
}

// 删除用户
const handleDeleteUser = async (row) => {
  try {
    // 二次确认
    if (!window.confirm(`确定要删除用户【${row.username}】吗？此操作不可恢复！`)) return;
    const token = getToken();
    if (!token) {
      ElMessage.warning('请先登录');
      return;
    }
    await request.delete(`/api/users/${row.id}/`);
    ElMessage.success('删除用户成功');
    refreshUsers();
  } catch (error) {
    console.error('删除用户失败:', error);
    ElMessage.error('删除用户失败: ' + (error.response?.data?.detail || error.message));
  }
}

onMounted(() => {
  console.log('UserManagement组件已挂载')
  refreshUsers()
})
</script>

<style scoped>
.admin-user-management {
  padding: 24px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.loading-container {
  padding: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 